<?php

namespace teach\controllers;

use teach\service\Kafka;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\Cors;
use yii\rest\ActiveController;
use yii\web\Response;

class KafkaController extends ActiveController
{
    public $modelClass = '';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 86400,
            ],
        ];
        return $behaviors;
    }

    /**
     * 测试php发送消息给kafka
     */
    public function actionTest()
    {
        $request = Yii::$app->request;
        $data = $request->post("data");

        $msg = "";
        $flag = false;
        if (!$data) {
            $msg = "data 不能为空";
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $kafka = new Kafka();
            $kafka->sendMsg($data);
            $jsonData = ResponseHelper::buildJsonData(200, "已发送");
        }
        return $this->asJson($jsonData);
    }

    public function actionTestMsg()
    {
        //{
        //"state":1,
        //"message":
        //{"uid":10014,
        // "mid":10000,
        // "openid":"oLAZ75aa9tYmJB3mIaLzMfOBcAkA",
        //"out_trade_no":"1111",
        // "phone":"13924486444",
        // "name":"温思尧",
        //"logistics":"jd",
        //"order_num":"222",
        // "tip":"商品已经发货,具体物流信息请在小程序中查看" }}
        $data["state"] = 1;
        $data["message"] = [
            "uid" => 10014,
            "mid" => 10000,
            "openid" => "oLAZ75aa9tYmJB3mIaLzMfOBcAkA",
            "out_trade_no" => "444",
            "phone" => "12924486444",
            "name" => "温思尧",
            "logistics" => "jd",
            "order_num" => "444",
            "tip" => "商品已经发货,具体物流信息请在小程序中查看"
        ];
        $dataStr = json_encode($data, true);
        $kafka = new Kafka();
        $kafka->sendMsg($dataStr);
        $jsonData = ResponseHelper::buildJsonData(200, "已发送");
        return $this->asJson($jsonData);
    }

}